package eip.chapter5.messagefilter.mule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mule.umo.UMOFilter;
import org.mule.umo.UMOMessage;

import eip.chapter5.messagefilter.DeclarationMessage;

/**
 * This filter keeps track of the messages that have already been
 * sent. If a duplicate message arrives the message is ignored.
 * 
 * @author nl24167
 */
public class DoubleDeclarationFilter implements UMOFilter {
	
	private Map<String,List<String>> receivedDeclarations = new HashMap<String,List<String>>();

	/**
	 * This method checks if we've already received this id. If we did we return false,
	 * if not we return true.
	 */
	public boolean accept(UMOMessage message) {
		if (message.getPayload() instanceof DeclarationMessage) {
			
			DeclarationMessage msg = (DeclarationMessage) message.getPayload();
			String declarationId = msg.getDeclarationId();
			String hotelId = msg.getHotelId();
			
			if (!receivedDeclarations.containsKey(hotelId)) {
				receivedDeclarations.put(hotelId,new ArrayList<String>());
				receivedDeclarations.get(hotelId).add(declarationId);
				return true;
			} else {
				if (receivedDeclarations.get(hotelId).contains(declarationId)) {
					return false;
				} else {
					receivedDeclarations.get(hotelId).add(declarationId);
					return true;	
				}
			}
		} else {
			return false;
		}
	}

}
